package xyz.chaobei.mall.common.exceptions;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import xyz.chaobei.common.api.CommonResult;
import xyz.chaobei.common.api.ResultCode;
import xyz.chaobei.common.exception.ApiException;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@RestControllerAdvice
@Slf4j
public class GlobalExControllerHandler {

    /**
     * <p>全局异常拦截器，拦截自定义ApiException
     * <p>author: <a href='mailto:maruichao52@gmail.com'>MRC</a>
     *
     * @param e 自定义异常
     * @return xyz.chaobei.common.api.CommonResult
     * @since 2020/10/20
     **/
    @ExceptionHandler(value = ApiException.class)
    public CommonResult exceptionHandler(ApiException e) {
        log.info("系统异常拦截器,拦截到异常信息");
        log.error("系统异常拦截器：自定义异常" , e);
        if (Objects.nonNull(e.getErrorCode())) {
            return CommonResult.failed(e.getErrorCode());
        }
        return CommonResult.failed(e.getMessage());
    }

    /**
     * <p>捕获一个参数校验异常信息，返回给前端
     * <p>author: <a href='mailto:maruichao52@gmail.com'>MRC</a>
     *
     * @param e 异常信息
     * @return xyz.chaobei.common.api.CommonResult
     * @since 2021/1/15
     **/
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public CommonResult exceptionHandler(MethodArgumentNotValidException e) {
        log.error("exceptionHandler：参数异常" , e);

        BindingResult bindingResult = e.getBindingResult();
        List<FieldError> fieldErrorList = bindingResult.getFieldErrors();

        Map<String, String> result = new HashMap<>();
        fieldErrorList.stream().forEach(item -> result.put(item.getField(), item.getDefaultMessage()));

        log.info("exceptionHandler 参数异常信息={}" , result.toString());

        return CommonResult.validateFailed(result);
    }

    /**
     * <p>捕获请求类型不支持异常信息，并返回信息
     * <p>author: <a href='mailto:maruichao52@gmail.com'>MRC</a>
     *
     * @param e 异常信息
     * @return xyz.chaobei.common.api.CommonResult
     * @since 2021/1/15
     **/
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public CommonResult exceptionHandler(HttpRequestMethodNotSupportedException e) {
        log.error("exceptionHandler：捕获类型不支持异常信息" , e);
        return CommonResult.failed(ResultCode.METHOD_NOT_ALLOWED);
    }

}